package com.mybatis.demo2;

import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class MainApp {
	private static SqlSessionFactory sqlSessionFactory;
	private static Reader reader;
	static{
		try{
			reader = Resources.getResourceAsReader("mybatis2.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 返回User单实例(配置)
	 */
	public void testDemo(){
		SqlSession session = sqlSessionFactory.openSession();
		try {
			User user = (User) session.selectOne("com.mybatis.demo2.UserOperation.selectUserByID", 1);
			System.out.println(user);
			
			List<Object> list =(List<Object>) session.selectList("com.mybatis.demo2.UserOperation.selectUsers", "%");
			System.out.println("list:"+list);
		} finally {
			session.close();
		}
	}
	/**
	 * 关联数据查询(配置)
	 */
	public void testDemo1(){
		SqlSession session = sqlSessionFactory.openSession();
		try {
			List<Object> user = (List<Object>) session.selectList("com.mybatis.demo2.UserOperation.getUserArticles");
			System.out.println(user);
		} finally {
			session.close();
		}
	}
	/**
	 * 关联数据查询(接口)
	 */
	public void testDemo1_(){
		SqlSession session = sqlSessionFactory.openSession();
		try {
			UserOperation userOperation = session.getMapper(UserOperation.class);
			Article user = userOperation.getUserArticles(1);
			System.out.println(user);
		} finally {
			session.close();
		}
	}
	/**
	 * 关联数据查询2(配置)
	 */
	public void testDemo2(){
		SqlSession session = sqlSessionFactory.openSession();
		try {
			Article user = (Article) session.selectOne("com.mybatis.demo2.UserOperation.getUserArticles-2", 1);
			System.out.println("2:"+user);
		} finally {
			session.close();
		}
	}
	public static void main(String[] args) {
//		System.out.println("单实例(配置)============");
		new MainApp().testDemo();
//		System.out.println("关联数据查询(配置)============");
		new MainApp().testDemo1();
//		System.out.println("关联数据查询(接口)============");
//		new MainApp().testDemo1_();
//		System.out.println("关联数据查询2(配置)============");
		new MainApp().testDemo2();
		
	}

}
